package com.sharad.quizbowl.ui.server;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Arrays;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class DownloadServlet extends HttpServlet {

	/**
	 * 
	 */
	private static final long serialVersionUID = 5974850105966910658L;

	@Override
	public void doGet(HttpServletRequest request, HttpServletResponse response) {
		doPost(request, response);
	}

	@Override
	public void doPost(HttpServletRequest request, HttpServletResponse response) {
		String text = request.getParameter("text");
		String format = request.getParameter("format");
		response.setContentType("application/x-download");
		try {
			if (format.equals(".pdf")) {
				Document document = new Document();

				response.setHeader("Content-Disposition",
						"attachment; filename=" + "exported.pdf");

				PdfWriter.getInstance(document, response.getOutputStream());
				document.open();
				String[] split = text.split("\\\\n");
				for (int i = 0; i < split.length; i++) {

					document.add(new Paragraph(split[i]));
				}
				document.close();
			} else if (format.equals(".txt")) {
				PrintWriter writer = response.getWriter();
				response.setHeader("Content-Disposition",
						"attachment; filename=" + "exported.txt");

				String[] split = text.split("\\\\n");
				for (int i = 0; i < split.length; i++) {
					writer.write(split[i] + "\n");
				}
				writer.close();
			}

		} catch (IOException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
